# coding: utf8

import os
import json
import time
import logging
import traceback
from http.server import ThreadingHTTPServer
from http.server import BaseHTTPRequestHandler
import mysql.connector.pooling
from datetime import datetime

logging.basicConfig(level=logging.INFO)


class SQLHelper(object):

    def __init__(self):
        config = {
            "user": 'root',
            "password": 'gt',
            "host": '127.0.0.1',
            "port": '3306',
            "database": 'db_expert'
        }

        try:
            self.ctxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name='mypool', pool_size=os.cpu_count() * 4, **config)
            logging.info("connect to mysql 127.0.0.1:3306//db_expert")
        except mysql.connector.Error as e:
            traceback.print_exc()
            raise e
        pass

    def close(self):
        pass

    def insert_expert(self, data):
        keys = ['name', 'institute', 'department', 'title', 'degree', 'tel', 'email', 'addr', 'avatar', 'edu', 'work', 'research', 'contribution', 'introduction', 'source', 'url']

        ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        sql = "INSERT INTO `tb_expert`(`name`, `institute`, `department`, `title`, `degree`, `tel`, `email`, `addr`, `avatar`, `edu`, `work`, `research`, `contribution`, `introduction`, `source`, `url`, `visit_time`) VALUES" \
              "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"

        data = [data.get(key, '') for key in keys] + [ts, ]
        assert data[0] != '', "name must be given! data: %s" % repr(data)

        def get_conn():
            try:
                __conn = self.ctxpool.get_connection()
            except mysql.connector.errors.PoolError as e:
                # raise e
                __conn = None
            return __conn

        conn = get_conn()
        while not conn:
            time.sleep(1)
            conn = get_conn()

        try:
            cursor = conn.cursor()

            cursor.execute(sql, data)
            conn.commit()

            row = cursor.lastrowid
            return row
        except mysql.connector.Error as e:
            logging.warning("sql data: %s", data)
            traceback.print_exc()
            raise e
        finally:
            conn.close()  # return to the pool


helper = SQLHelper()


class SQLRequestHandler(BaseHTTPRequestHandler):

    def _set_response(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        data = self.rfile.read(content_length)
        data = json.loads(data.decode('utf-8'))
        # logging.info("data: %s", data)

        row = helper.insert_expert(data)

        self._set_response()

        msg = {'msg': 'ok!', 'row': row}
        self.wfile.write(str.encode(json.dumps(msg, ensure_ascii=False)))
        self.wfile.flush()


def run(server_class=ThreadingHTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8088)
    httpd = server_class(server_address, handler_class)
    logging.info("http server start at port %s", 8088)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info("http server closed.")

    pass


if __name__ == '__main__':
    run(ThreadingHTTPServer, SQLRequestHandler)
    helper.close()
    pass






